﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 限定最大长度, 示例:
/// <code>
/// [VMaxLength(400)]
/// public string Remark { get; set; }
/// </code>
/// </summary>
/// <remarks>
/// 注意: 
/// <list type="bullet">
/// <item>当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</item>
/// <item>当字符串为null时, 验证直接通过</item>
/// </list>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMaxLengthAttribute(int max, string errorMessage = null) : Attribute, IValidateAction
{
    public int Max { get; set; } = max;
    public string ErrorMessage { get; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustMaxLengthInternal(ctx, ctx.ModelValue?.ToString(), Max, ErrorMessage);
    }
}
